﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using yc.Dal;

namespace yc.Site.Controllers
{
	public class DictionaryController : Controller
	{
		public ActionResult Index()
		{
			var pager = Common.Dictionary.AsQueryable().ToPager("Category");
			ViewBag.Category = Common.UnSelect.Union(new SelectList(Common.Dictionary.Select(p => p.Category).OrderBy(p => p).Distinct(), Request["Category"]));
			return View(pager);
		}

		public ActionResult Edit(int Id = 0)
		{
			var item = Common.Dictionary.Find(p => p.ID.Equals(Id)) ?? new SysDictionary();
			return View(item);
		}

		[HttpPost, ActionName("Edit")]
		public ActionResult PostEdit(SysDictionary item)
		{
			if (ModelState.IsValid)
			{
				var db = new DBContext();
				db.Configuration.AutoDetectChangesEnabled = true;
				if (item.ID > 0)
				{
					db.SysDictionary.Attach(item);
					db.Entry(item).State = System.Data.EntityState.Modified;
					var tmp = Common.Dictionary.Find(p => p.ID.Equals(item.ID));
					TryUpdateModel(tmp);
				}
				else
				{
					db.SysDictionary.Add(item);
					Common.Dictionary.Add(item);
				}
				db.SaveChanges();
				ViewBag.Saved = 1;
				ModelState.AddModelError("", "保存成功");
			}
			return View(item);
		}

		[HttpPost]
		public ActionResult Del(int id = 0)
		{
			if (id == 0) return Json(new { res = false, msg = "数据非法" });
			var db = new DBContext();
			db.Configuration.AutoDetectChangesEnabled = true;
			var item = db.SysDictionary.Find(id);
			if (item == null) return Json(new { res = false, msg = "数据非法" });
			db.SysDictionary.Remove(item);
			db.SaveChanges();
			Common.Dictionary.RemoveAll(p => p.ID.Equals(id));
			return Json(new { res = true, msg = "删除成功" });
		}

	}
}
